//
//  KLOrderViewController.m
//  KunLun
//
//  Created by Mac on 2017/11/28.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "KLOrderViewController.h"
#import "KLOrderHeaderView.h"
#import "KLOrderFooterView.h"
#import "KLOrderTableViewCell.h"
#import "KLOrderModel.h"
#import "STActionSheet.h"
#import "KLOrderDetailViewController.h"
#import "KLCommentGoodViewController.h"
@interface KLOrderViewController ()<STActionSheetDelegate>
@property(nonatomic, strong) NSArray                               *titleArray;
@property(nonatomic, strong) STSegementButton                     *segementButton;
@property(nonatomic, strong) STNoresultView                     *noResultView;
@property(nonatomic, strong) NSMutableArray<KLOrderModel*>                     *dataSouce;
@property(nonatomic, strong) KLOrderModel                     *currentSelctedModel;
@end

@implementation KLOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _titleArray = @[@"全部",@"待付款",@"待发货",@"待收货",@"待评价",@"已完成"];
    self.title = @"我的订单";
    [self configSubView];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    
    self.segementButton = [[STSegementButton alloc] initWithFrame:CGRectMake(0, 64, UIScreenWidth, 44)
                                                         andTitle:_titleArray handle:^(STSegementButton *sender) {
                                                             
                                                             [weakSelf.tableView.mj_header beginRefreshing];
                                                         }];
    self.segementButton.backgroundColor = [UIColor whiteColor];
    self.segementButton.lineSelectedColor = KL_BlueBackGroundColor;
    self.segementButton.butTitleSelectedColor = KL_BlueBackGroundColor;
    self.segementButton.butTitleColor = KL_secendTextColor;
    self.segementButton.lineColor = [UIColor whiteColor];
    self.segementButton.cureentIndex = 0;
    self.segementButton.autoMoveWithClic = YES;
    [self.view addSubview:self.segementButton];
    
    self.tableView.st_top = self.tableView.st_top + 44 ;
    self.tableView.st_height =  self.tableView.st_height - 44 ;
    //无数据view
    self.noResultView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, 100, UIScreenWidth, 350) title:@"暂无相关订单" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.noResultView.hidden = YES;
    [self.tableView addSubview:self.noResultView];
    //header
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendMyorderRequest];
    }];
    [self.tableView.mj_header beginRefreshing ];


    //注册重用
    [self.tableView registerClass:[KLOrderHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.tableView registerClass:[KLOrderFooterView class] forHeaderFooterViewReuseIdentifier:@"footer"];
    [self.tableView registerClass:[KLOrderTableViewCell class] forCellReuseIdentifier:@"cell"];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce[section].goodsorder.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [KLOrderTableViewCell CellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return [KLOrderHeaderView headerHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return [KLOrderFooterView footerHeight];
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    KLOrderHeaderView * header = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    header.model = self.dataSouce[section];
    return header;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    KLOrderFooterView * footer = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
    footer.model = self.dataSouce[section];
    __weak typeof(self) weakSelf =  self;
    [footer.menuButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelcedMenuButtonWithButton:sender section:section];
    }];

    return footer;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    KLOrderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.model = self.dataSouce[indexPath.section].goodsorder[indexPath.row];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    KLOrderModel *  model = self.dataSouce[indexPath.section];
    KLOrderDetailViewController * vc = [KLOrderDetailViewController new];
    vc.orderID = model.orderID.description;
    [self.navigationController pushViewController:vc animated:YES];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Private Method
- (void)reloadData{
    self.noResultView.hidden = self.dataSouce.count;
    [self.tableView reloadData];
}
- (NSString*)currentType{
    switch (self.segementButton.cureentIndex) {
        case 0:
            return @"";
            break;
        case 1:
            return @"0";
            break;
        case 2:
            return @"1";
            break;
        case 3:
            return @"2";
            break;
        case 4:
            return @"3";
            break;
        case 5:
            return @"9";
            break;
        default:
            break;
    }
    return @"";
}
#pragma mark --Action Method
- (void)onSelcedMenuButtonWithButton:(UIButton*)button section:(NSInteger)section{
    KLOrderModel * model = self.dataSouce[section];
    self.currentSelctedModel = model;
    if ([button.currentTitle isEqualToString:@"付款"]) {
        if (model.goodsorder.firstObject.classification.integerValue == 4) {
            [SVProgressHUD showInfoWithStatus:@"菜园子商品只能线下交易"];
            return;
        }
        [self showPayStyle];
    }
    if ([button.currentTitle isEqualToString:@"评价"]) {
        KLCommentGoodViewController * vc = [KLCommentGoodViewController new];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([button.currentTitle isEqualToString:@"确认收货"]) {
        [self sendConfimRequestWithModel:model];
    }
    if ([button.currentTitle isEqualToString:@"再次评价"]) {
        KLCommentGoodViewController * vc = [KLCommentGoodViewController new];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
- (void)showPayStyle{
    STActionSheet  * action = [STActionSheet actionSheetWithTitle:@"支付方式" buttonTitles:@[@"微信",@"支付宝"] cancelTitle:@"取消" delegate:self];
    [action show];
}
#pragma mark --STActionSheetDelegate
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //微信
        [self sendPayOrderRequestWithModel:_currentSelctedModel type:@"wxpay"];
    }
    if (buttonIndex == 1) {
        //支付宝
          [self sendPayOrderRequestWithModel:_currentSelctedModel type:@"alipay"];
    }
}
#pragma mark --NetWork Method
- (void)sendMyorderRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/orderlist",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    NSString * numString = [self currentType];
    if (numString.length) {
        [dic setObject:numString forKey:@"type"];
    }
   
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * array =  responseObject[@"data"][@"order_list"];
                                                 self.dataSouce = [NSMutableArray new];
                                                 NSLog(@"json = %@",array.mj_JSONString);
                                                 for (NSDictionary * modelDIc in array) {
                                                     KLOrderModel * model = [KLOrderModel mj_objectWithKeyValues:modelDIc];
                                                     
                                                     NSMutableArray * goods = modelDIc[@"goodsorder"];
                                                     NSMutableArray * goodsArray = [NSMutableArray new];
                                                     for (NSDictionary * goodDic in goods) {
                                                         KLOrderGoodModel * good = [KLOrderGoodModel mj_objectWithKeyValues:goodDic];
                                                         [goodsArray addObject:good];
                                                     }
                                                     model.goodsorder = goodsArray;
                                                     
                                                     [self.dataSouce addObject:model];
                                                     
                                                     
                                                 }
                                                 [self reloadData];

                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendPayOrderRequestWithModel:(KLOrderModel*)model type:(NSString*)type{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (self.currentSelctedModel) {
        [dic setObject:self.currentSelctedModel.orderID forKey:@"order_id"];
    }
    [dic setObject:type forKey:@"pay_type"];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/order/payagain",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"pay_data"]) {
                                                     if ([type isEqualToString:@"wxpay"]) {
                                                         NSDictionary * wechatDic = dataDic[@"pay_data"];
                                                         //wechat
                                                         PayReq *request = [PayReq new];
                                                         request.nonceStr = wechatDic[@"noncestr"];
                                                         request.package = wechatDic[@"package"];
                                                         request.partnerId = wechatDic[@"partnerid"];
                                                         request.prepayId = wechatDic[@"prepayid"];
                                                         request.sign = wechatDic[@"sign"];
                                                         request.timeStamp = [wechatDic[@"timestamp"] intValue];
                                                         [WXApi sendReq:request];
                                                     }else{
                                                         NSString * alipayStr = dataDic[@"pay_data"];
                                                         //alipay
                                                         [[AlipaySDK defaultService] payOrder:alipayStr fromScheme:@"KunLun" callback:^(NSDictionary *resultDic) {
                                                             NSLog(@"reslut = %@",resultDic);
                                                             //回调在appdelegate 中
                                                         }];
                                                     }
                                                 }
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
//确认收货
- (void)sendConfimRequestWithModel:(KLOrderModel*)model{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (model) {
        [dic setObject:model.orderID forKey:@"order_id"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/confirmorder",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                  [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"确认收货成功"];
                                                 [self.tableView.mj_header beginRefreshing];
                                                
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
